import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base_notifier.dart';

// 用户详细信息模型
class UserProfile {
  final int id;
  final String name;
  final String email;
  final String avatar;
  final DateTime lastLogin;

  const UserProfile({
    required this.id,
    required this.name,
    required this.email,
    required this.avatar,
    required this.lastLogin,
  });

  @override
  String toString() => 'UserProfile(id: $id, name: $name, email: $email)';
}

// 异步初始化的用户 Notifier
class AsyncUserProfileNotifier extends BaseAsyncNotifier<UserProfile> {
  @override
  Future<BaseState<UserProfile>> build() async {
    // 异步初始化，立即开始加载数据
    await loadData();
    return state.value ?? const BaseState();
  }

  @override
  Future<void> loadData({bool isRefresh = false}) async {
    await executeAsync(
      () => _fetchUserProfile(),
      isRefresh: isRefresh,
    );
  }

  // 模拟异步获取用户详细信息
  Future<UserProfile> _fetchUserProfile() async {
    // 模拟网络延迟
    await Future.delayed(const Duration(seconds: 2));

    // 模拟错误情况
    if (DateTime.now().millisecond % 5 == 0) {
      throw Exception('获取用户信息失败');
    }

    return UserProfile(
      id: 1001,
      name: '王五',
      email: 'wangwu@example.com',
      avatar: 'https://example.com/avatar.jpg',
      lastLogin: DateTime.now().subtract(const Duration(hours: 2)),
    );
  }

  // 更新用户资料
  Future<void> updateProfile({
    String? name,
    String? email,
  }) async {
    final currentData = state.value?.data;
    if (currentData == null) return;

    await executeAsync(
      () => _updateProfile(currentData, name: name, email: email),
      keepDataOnError: true,
    );
  }

  Future<UserProfile> _updateProfile(
    UserProfile currentProfile, {
    String? name,
    String? email,
  }) async {
    await Future.delayed(const Duration(seconds: 1));

    return UserProfile(
      id: currentProfile.id,
      name: name ?? currentProfile.name,
      email: email ?? currentProfile.email,
      avatar: currentProfile.avatar,
      lastLogin: currentProfile.lastLogin,
    );
  }
}

// Provider 定义
final asyncUserProfileProvider = AsyncNotifierProvider<AsyncUserProfileNotifier, BaseState<UserProfile>>(() {
  return AsyncUserProfileNotifier();
});

// 基于用户信息的计算属性
final userDisplayNameProvider = Provider<String>((ref) {
  final userState = ref.watch(asyncUserProfileProvider);

  return userState.when(
    data: (state) {
      if (state.hasData) {
        return state.data!.name;
      }
      return '未知用户';
    },
    loading: () => '加载中...',
    error: (_, __) => '加载失败',
  );
});